//
//  MainViewController.m
//  UIScrollView
//
//  Created by cocoazxj@163.com on 15/3/24.
//  Copyright (c) 2015年 handcool. All rights reserved.
//

#import "MainViewController.h"

@interface MainViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) IBOutlet UIScrollView *sv_ad;
@property (nonatomic, strong) IBOutlet UIPageControl *pc_point;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.sv_ad.delegate = self;
    [self dynamicImageView];
    [self addNSTimer];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/* ***********************************************
 1.两种添加计时器的方法:
   scheduledTimerWithTimeInterval
   timerWithTimeInterval
   第一个，自动添加到mainRunLoop
 
 ********************************************** */

- (void)addNSTimer
{
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(nextPageNum) userInfo:nil repeats:YES];
    self.timer = [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(nextPageNum) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}

- (void)removeNSTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)nextPageNum
{
    int page;
    page = self.pc_point.currentPage;
    page ++;
    if (page == 5)
    {
        page = 0;
    }
    [self.sv_ad setContentOffset:CGPointMake(320*page, 0) animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.pc_point.currentPage = (self.sv_ad.contentOffset.x + 165)/320;
}

        /* *************************************
         1.手动滚动时，应该停止计时器。
         2.
 
         ************************************ */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self removeNSTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self addNSTimer];
}

- (void)dynamicImageView
{
    CGFloat width = [[UIScreen mainScreen] bounds].size.width;
    CGFloat height = self.sv_ad.frame.size.height;
    // 设置ScrollView的大小（包括隐藏的部分）
    // 设置ScrollView的翻页
    self.sv_ad.contentSize = CGSizeMake(5*width, height);
    self.sv_ad.pagingEnabled = YES;
    
    self.pc_point.numberOfPages = 5;
    
    for (int i = 0 ; i < 5; i++)
    {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i*width, 0, width,height)];
        imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"ad_%d",i]];
        [self.sv_ad addSubview:imageView];
    }
}
@end
